//
//  MYGCaseSearchResultViewController.swift
//  MYGrow
//
//  Created by 王振明 on 2024/4/21.
//

import UIKit

class MYGCaseSearchResultViewController: UIViewController {
    var searchContent:String = ""
    private var contents:[[MYGCaseSubModel]] = []
    private var array:[MYGCaseSubModel] = []
    private var  titles:[String] = []
    private var newcontents:[[[MYGCaseSubModel]]] = []
    private var newarray:[[MYGCaseSubModel]] = []
    private var  newtitles:[[String]] = []
    private var  sectionTitleArr:[String] = []
    private var  segmentSelectNum:[Int] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        getCaseFileInfo()
        headSearchBar.text = searchContent
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        self.navigationController?.isNavigationBarHidden = true
    }
    @objc func clickBackBtn(){
        navigationController?.popViewController(animated: true)
    }
    private func initUI(){
        view.backgroundColor = .white

        view.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
        view.addSubview(headSearchBar)
        headSearchBar.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(44)
            make.centerY.equalTo(backBtn)
            make.height.equalTo(SCALEWIDTH(30))
            make.right.equalToSuperview().offset(-SCALEWIDTH(20))
        }
        view.addSubview(casesDetailTable)
        casesDetailTable.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(headSearchBar.snp.bottom).offset(10)
        }
    }
    private lazy var backBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "Common/back"), for: .normal)
        btn.imageView?.tintColor = .rgba(51, 51, 51, 1)
        btn.addTarget(self, action: #selector(clickBackBtn), for: .touchUpInside)
        return btn
    }()
    private lazy var headSearchBar:UITextField = {
       let cont = UITextField()
        cont.placeholder = "🔍搜索"
        cont.backgroundColor = .rgba(243, 243, 243)
        cont.font = .regular(13)
        cont.returnKeyType = .search
        cont.delegate = self
        cont.layerCornerRadius = SCALEWIDTH(15)
        cont.layerShadowColor = .rgba(0, 0, 0, 1)
        cont.layer.shadowOffset = CGSize(width: 1, height: 1)
        cont.layer.shadowRadius = 7
        cont.layer.shadowOpacity = 1
        return cont
    }()
    private lazy var casesDetailTable: UITableView = {
        let cont = UITableView(frame: CGRectZero, style: .grouped)
        cont.delegate = self
        cont.dataSource = self
        cont.separatorStyle = .none
        cont.backgroundColor = .clear
        cont.showsVerticalScrollIndicator = false
        return cont
    }()
}

extension MYGCaseSearchResultViewController:UITextFieldDelegate{
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        searchContent = textField.text ?? ""
        textField.resignFirstResponder()
        contents.removeAll()
        array.removeAll()
        titles.removeAll()
        newcontents.removeAll()
        newarray.removeAll()
        newtitles.removeAll()
        sectionTitleArr.removeAll()
        segmentSelectNum.removeAll()
        
        getCaseFileInfo()
        return true
    }
}
extension MYGCaseSearchResultViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitleArr.count
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let vi = MYGCaseFileCellHeaderView()
        vi.defautIndex = segmentSelectNum[section]
        vi.titleStr = sectionTitleArr[section]
        vi.titles = newtitles[section]
        vi.searchButton.isHidden = true
        vi.slectDate = {[self] value in
            self.newarray[section] = self.newcontents[section][value]
            segmentSelectNum[section] = value
            self.casesDetailTable.reloadData()
        }
        return vi
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SCALEWIDTH(100)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newarray[section].count
        return self.array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MYGCaseFilesDetailCell(style: .default, reuseIdentifier: "MYGCaseFilesDetailCell")
        cell.selectionStyle = .none
        cell.model = newarray[indexPath.section][indexPath.row]
//        cell.model = array[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        108
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = MYGCaseFilesViewController()
        vc.data = newarray[indexPath.section][indexPath.row]

        navigationController?.pushViewController(vc)
    }
    
}

extension MYGCaseSearchResultViewController {
    func getCaseFileInfo () {
        MYGLoading.show()
        let patient_id:Int = 0
        MMYGNetwork<MYGCaseFilesApi,MYGCaseModel>.request(target: .getClassClamp(patient_id: "\(patient_id)", serche: searchContent)) { [self] item in
            MYGLoading.hide()
            guard let items = item?.data,items.count > 0 else {
                return
            }
            
            item?.data.forEach({ model in
                var newArr:[String] = []
                var newconArr:[[MYGCaseSubModel]] = []

                model.months.forEach { caseModel in
                    //print(caseModel.count,caseModel.month_name)
                    let arr = caseModel.lists
                    self.contents.append(arr)
                    newconArr.append(arr)
                    let title:String = "\(caseModel.month_name)(\(caseModel.count))"
                    self.titles.append(title)
                    newArr.append(title)
                }
                self.newcontents.append(newconArr)
                segmentSelectNum.append(0)
                self.newtitles.append(newArr)
                self.sectionTitleArr.append("\(model.year)(\(model.count))")
            })
            //print(contents,titles)
//            self.headerView.titles = self.titles
            self.array = self.contents.first!
            for ind in 0...self.newcontents.count - 1{
                let arr = self.newcontents[ind][0]
                self.newarray.append(arr)
            }
            self.casesDetailTable.reloadData()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }


}
